<template>
  <div>
    <el-button type="primary" @click="clickAddProcess">添加加工过程</el-button>
    <el-table :data="data.processTableData" style="width: 100%">
      <el-table-column prop="processId" label="加工编号" width="180"> </el-table-column>
      <el-table-column prop="name" label="加工步骤" width="180"> </el-table-column>
      <el-table-column prop="time" label="加工时间" width="180"> </el-table-column>
      <el-table-column prop="produceAddress" label="加工地址" width="180">

      </el-table-column>
      <el-table-column prop="note" label="备注" width="180"> </el-table-column>
      <el-table-column prop="certification" label="加工证明图片" width="180">
        <template #default="scope">
          <el-button type="primary" @click="checkCertification(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
        v-model="data.addProcessVisible"
        title="新增加工过程"
    >
      <el-form :model="data.addProcessForm">
        <el-form-item label="加工编号" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProcessForm.processId" disabled></el-input>
        </el-form-item>
        <el-form-item label="产品ID" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProcessForm.productId" disabled></el-input>
        </el-form-item>
        <el-form-item label="加工步骤" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProcessForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="加工时间" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProcessForm.time" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="加工地址" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProcessForm.produceAddress" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="备注" :label-width="data.formLabelWidth">
          <el-input v-model="data.addProcessForm.note" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="加工证明图片" :label-width="data.formLabelWidth">
          <UploadPic @getUploadHash="getHash"/>
        </el-form-item>
      </el-form>
      <template #footer>
          <span class="dialog-footer">
            <el-button @click="data.addProcessVisible = false">取消</el-button>
            <el-button type="primary" @click="handleAddProcess">确认</el-button>
          </span>
      </template>
    </el-dialog>
    <el-dialog v-model="data.certificationVisible">
      <img class="certification" :src="data.certificationSrc" />
    </el-dialog>
  </div>
</template>

<script>
import {onMounted, reactive} from "vue";
import { useStore } from "vuex";
import { useRoute,useRouter } from "vue-router";
import {v1 as uuidv1} from "uuid";
import {
  func_addProcess,
  func_getAddress, func_getProductById,
  func_getUserInfo,
  func_getUserProcess,
  func_getUserRole
} from "../../../api/etherneum/api";
import UploadPic from "@/components/UploadPic/index";
import ipfsAPI from "ipfs-api";
import {getYMD} from "../../../utils/TimeStamp";
import {ElMessage} from "element-plus";
const ipfs = ipfsAPI({ host: "49.234.138.61", port: "5001", protocol: "http" });
export default {
  name: "ProcessDetail",
  components:{
    UploadPic
  },
  setup(){
    const store=useStore();
    const route=useRoute();
    const data=reactive({
      productId:route.params.productId || store.getters["crops/productId"],
      processTableData:[
          {}
      ],
      addProcessForm:{},
      formLabelWidth:'140px',
      addProcessVisible:false,
      processIsVisible:false,
      processForm:{
        cropId:'',
        temp:'',
        growth:'',
        water:'',
        sunlight:'',
        note:'',

      },
      productInfo:{},
      certificationVisible:false,
      certificationSrc:''
    })
    const clickAddProcess=()=>{
      if (data.curUserInfo.role!=1&&(data.curUserInfo.role!=4||data.address!=data.productInfo.owner)){
        ElMessage.error('无权限')
        return
      }
      data.addProcessVisible=true
      console.log(route.params.productId)
      data.addProcessForm.processId=uuidv1()
      data.addProcessForm.productId=data.productId
      data.addProcessForm.time=getYMD(new Date())
    }

    const handleAddProcess=()=>{
      if (!data.addProcessForm.certification){
        ElMessage.error('图片未上传')
        return
      }
      func_addProcess(data.addProcessForm,0)
      data.addProcessVisible=false

    }

    const getAddress = async () => {
      const address = await func_getAddress();
      if (address) {
        store.commit("app/SET_ADDRESS", address);
        let role = await func_getUserRole(address);
        store.commit("app/SET_ROLE", role);
        console.log("getUser address=" + address + " role=" + role);
        data.address = address;
        data.currentRole = role;
        data.curUserInfo = await func_getUserInfo(data.address);
        console.log("cur:" + data.curUserInfo.requestRole);
      }
    };
    const getHash=(hash)=>{
      data.addProcessForm.certification=hash
    }

    const checkCertification=async (row)=>{
      let hash=row.certification
      data.loading=true
      console.log('certification:',row.certification)
      ipfs.get(hash, async (err, result) => {
        console.log('here')
        if (err) throw err;
        let binaryData = [];
        binaryData.push(result[0].content.buffer);
        data.certificationSrc= window.URL.createObjectURL(new Blob(binaryData))
        console.log('src=',data.certificationSrc)
        data.loading=false
      });

      data.certificationVisible=true
    }

    onMounted(()=>{
      getAddress().then(async () => {
        let productId=route.params.productId
        data.productInfo=await func_getProductById(productId)
        console.log('productId:',productId)
        data.processTableData=await func_getUserProcess(productId,0)
        console.log(data.processTableData)
      });
      ethereum.on("accountsChanged", () => {
        getAddress();
      });
    })
    return{
      data,
      clickAddProcess,
      handleAddProcess,
      getHash,
      checkCertification
    }
  }
}
</script>

<style scoped>

</style>